package fr.utbm.aiechat.activities;

import fr.utbm.aiechat.LocalisationData;
import fr.utbm.aiechat.Network;
import fr.utbm.aiechat.R;
import fr.utbm.aiechat.Settings;
import fr.utbm.aiechat.Localisation;
import fr.utbm.aiechat.SharedFilesManager;
import fr.utbm.aiechat.localisation.MyLocationUpdater;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

public class AieChatActivity extends TabActivity implements OnTabChangeListener
{

    public static TabHost tabHost = null;
	private Localisation Localisation;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        // Prepare the Network
        Network.createInstance(this).start();
        
        // prepare the SharedFilesManager
        SharedFilesManager.createInstance(this);
        
        if(!SharedFilesManager.getInstance().started())
        	SharedFilesManager.getInstance().execute();
        
        // Select our main view.
        setContentView(R.layout.main);
        
        // Let's create the 3 Tabs.
        Resources res = getResources();
        tabHost = getTabHost();
        
        // First tab: the Conversations Tab
        Intent intent = new Intent().setClass(this, ConvsTabActivity.class);
        TabHost.TabSpec spec = tabHost.newTabSpec("home").setIndicator("Conversations", 
        		res.getDrawable(R.drawable.home_tab_icon))
        		.setContent(intent);
        tabHost.addTab(spec);
       
        
        // Second tab: the Channels Tab
        intent = new Intent().setClass(this, ChannelsTabActivity.class);
        spec = tabHost.newTabSpec("channels").setIndicator("Salons", 
        		res.getDrawable(R.drawable.channels_tab_icon))
        		.setContent(intent);
        tabHost.addTab(spec);
        
        // Third tab: the Users Tab
        intent = new Intent().setClass(this, UsersTabActivity.class);
        spec = tabHost.newTabSpec("users").setIndicator("Utilisateurs", 
        		res.getDrawable(R.drawable.users_tab_icon))
        		.setContent(intent);
        tabHost.addTab(spec);
        
        tabHost.setOnTabChangedListener(this);
        
        // Create the Settings Singleton Instance
        Settings.createInstance(this);
        
        LocalisationData.createInstance(this);
        Localisation = new Localisation(this);
        Localisation.execute();
        
        // Do we have a Nickname ??
        if(!Settings.getInstance().hasNickname() || (!Settings.getInstance().hasSexe()))
        {
        	// No ?? So let's ask for one.
        	final Dialog dialog = new Dialog(this);

        	dialog.setContentView(R.layout.pick_nickname);
        	dialog.setTitle("Choisissez un Pseudo");
        	
        	Button NickValidBtn = (Button) dialog.findViewById(R.id.NickValid);
        	final EditText NickEdit = (EditText) dialog.findViewById(R.id.NickEdit);
        	final Spinner sexesList = (Spinner) dialog.findViewById(R.id.sexesList);
        	
        	NickValidBtn.setOnClickListener(new View.OnClickListener()
        	{
                public void onClick(View v)
                {
                	// Let's save this Nickname
                	Settings.getInstance().setNickname(NickEdit.getText().toString());
                	//Let's save this sexe
                	Settings.getInstance().setSexe(sexesList.getSelectedItem().toString());
                	// Close the Dialog
                	dialog.dismiss();
                	// And finally start the network.
                	startDiscovery();
                }
            });

        	dialog.show();
        }
        
        else
        {
        	// if we already have a Nickname, then start the network right now
        	startDiscovery();
        }
        Network.getInstance().setMe();
       
      /*  User userF;
		try {
			userF = new User(InetAddress.getLocalHost(), "Female1", "Femme", 47.223830, 5.897461);
			Network.getInstance().addUser(userF);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        User userM;
		try {
			userM = new User(InetAddress.getLocalHost(), "Male1", "Homme", 47.621836, 6.825130);
			Network.getInstance().addUser(userM);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        */
        
        
		LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000 , 0, new MyLocationUpdater());

        String provider = LocationManager.GPS_PROVIDER;
        //TODO: Cause a nullPointerException
       /* location = locationManager.getLastKnownLocation(provider);
        System.out.println("The latitude is " + location.getLatitude() + "and " 
                + "the longitude is "+ location.getLongitude());*/
        
    }
    
    public void startDiscovery()
    {
    	Network.getInstance().discoverUsers();
        Network.getInstance().discoverChannels();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	int id = item.getItemId();
        // Handle item selection
        switch (id)
        {
	        case R.id.mapview:
	        	Intent MapViewActivity = new Intent(getBaseContext(), MapViewActivity.class);
	        	Bundle b = new Bundle();
	    		b.putString("typeView", "allUsers");
	    		MapViewActivity.putExtras(b);
            	startActivity(MapViewActivity);
	            return true;
        
            case R.id.settings:
            	Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
            	startActivity(settingsActivity);
                return true;
                
            case R.id.newchan:
            	// ask for the new Chan Name
            	final Dialog dialog = new Dialog(this);

            	dialog.setContentView(R.layout.pick_channelname);
            	dialog.setTitle("Choisissez un Nom de Salon");
            	
            	Button NickValidBtn = (Button) dialog.findViewById(R.id.ChannelValid);
            	final EditText NickEdit = (EditText) dialog.findViewById(R.id.ChannelEdit);
            	
            	NickValidBtn.setOnClickListener(new View.OnClickListener()
            	{
                    public void onClick(View v)
                    {
                    	// create the new Public Channel
                    	Network.getInstance().createChannel(NickEdit.getText().toString(), false);
                    	// Close the Dialog
                    	dialog.dismiss();
                    }
                });

            	dialog.show();
            	return true;
            	
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    
    public void onDestroy()
    {
    	super.onDestroy();
    	SharedFilesManager.getInstance().cancel(true);
    	Network.getInstance().stop();
    }
    

	@Override
	public void onTabChanged(String id)
	{
		if(id.equals("users"))
		{
			Network.getInstance().discoverUsers();
		}
		else if(id.equals("channels"))
		{
			Network.getInstance().discoverChannels();
		}
	}
}
